<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="电站" prop="stationId">
        <el-select @change="getList" v-model="queryParams.stationId" placeholder="请选择电站">
          <el-option v-for="(item, key) in station_list" :key="key" :label="item.stationName" :value="item.stationId" />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
        <el-button icon="Refresh" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button type="primary" plain icon="Plus" @click="handleAdd">新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="success" plain icon="Edit" :disabled="single" @click="handleUpdate">修改
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="danger" plain icon="Delete" :disabled="multiple" @click="handleDelete">删除
        </el-button>
      </el-col>
      <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="infoList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="套餐名称" align="center">
        <template #default="scope">
          <span v-if="scope.row.chargeType == 'ONCE'">
            {{ scope.row.amount / 100 }}元
            <span v-if="scope.row.chargeMode == 'TIME'">{{ (scope.row.duration / 3600).toFixed(1) + "小时" }}</span>
            <span v-if="scope.row.chargeMode == 'ELEC'">{{ (scope.row.electricity / 3600000).toFixed(1) + "度" }}</span>
            <span v-if="scope.row.chargeMode == 'GRADE'">(分档)</span>
          </span>
          <span v-if="scope.row.chargeType == 'WALLET'">{{ (scope.row.duration / 3600).toFixed(1) }}小时</span>
        </template>
      </el-table-column>
      <el-table-column label="预付金额" align="center" prop="amount">
        <template #default="scope">
          <span>{{ scope.row.amount / 100 }}元</span>
        </template>
      </el-table-column>
      <el-table-column label="预充时间" align="center" prop="duration">
        <template #default="scope">
          <span v-if="scope.row.chargeMode == 'TIME'">{{ parseInt(scope.row.duration / 60) }}分钟</span>
          <span v-if="scope.row.chargeMode != 'TIME'">-</span>
        </template>
      </el-table-column>
      <el-table-column label="预充电量" align="center" prop="electricity">
        <template #default="scope">
          <span v-if="scope.row.chargeMode == 'ELEC'">{{ (scope.row.electricity / 3600000).toFixed(1) }}度</span>
          <span v-if="scope.row.chargeMode != 'ELEC'">-</span>
        </template>
      </el-table-column>
      <el-table-column label="套餐类型" align="center" prop="chargeType">
        <template #default="scope">
          <dict-tag :options="charge_type" :value="scope.row.chargeType" />
        </template>
      </el-table-column>
      <el-table-column label="计费模式" align="center" prop="chargeMode">
        <template #default="scope">
          <dict-tag :options="charge_mode" :value="scope.row.chargeMode" />
        </template>
      </el-table-column>
      <el-table-column label="刷卡套餐" align="center" prop="isCard">
        <template #default="scope">
          <el-tag type="danger" v-if="scope.row.isCard == 0">否</el-tag>
          <el-tag type="success" v-if="scope.row.isCard == 1">是</el-tag>
        </template>
      </el-table-column>
      <!-- <el-table-column label="创建信息" align="center">
        <template #default="scope">
          <span class="modify">{{ scope.row.createBy || "-" }}</span>
          <span class="modify">{{
            parseTime(scope.row.createTime, "{y}-{m}-{d}")
          }}</span>
        </template>
      </el-table-column> -->
      <!-- <el-table-column label="更新信息" align="center">
        <template #default="scope">
          <span class="modify">{{ scope.row.updateBy || "-" }}</span>
          <span class="modify">{{
            parseTime(scope.row.updateTime, "{y}-{m}-{d}")
          }}</span>
        </template>
      </el-table-column> -->
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template #default="scope">
          <el-button type="text" icon="Edit" @click="handleUpdate(scope.row)">修改</el-button>
          <el-button type="text" icon="Delete" @click="handleDelete(scope.row)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination v-show="total > 0" :total="total" v-model:page="queryParams.pageNum" v-model:limit="queryParams.pageSize"
      @pagination="getList" />

    <!-- 添加或修改套餐对话框 -->
    <el-dialog :title="title" v-model="open" width="600px" append-to-body :close-on-click-modal="false">
      <el-form ref="formRef" :model="form" :rules="rules" label-width="120px">
        <el-form-item label="预付金额(元)" prop="amount">
          <el-input-number :min="0.01" :precision="2" v-model="form.amount" />
        </el-form-item>
        <el-form-item label="预充时间(分钟)" prop="duration" v-if="form.chargeMode == 'TIME'">
          <el-input-number v-model="form.duration" :min="1" :precision="0" />
        </el-form-item>
        <el-form-item label="预充电量(度)" prop="electricity" v-if="form.chargeMode == 'ELEC'">
          <el-input-number :min="0.01" :precision="2" v-model="form.electricity" />
        </el-form-item>
        <el-form-item label="套餐类型" prop="chargeType">
          <el-radio-group v-model="form.chargeType">
            <el-radio v-for="dict in charge_type" :key="dict.value" :label="dict.value">{{
              dict.label
            }}
            </el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="计费模式" prop="chargeMode" v-if="form.chargeType == 'ONCE'">
          <el-radio-group v-model="form.chargeMode">
            <el-radio v-for="dict in charge_mode" :key="dict.value" :label="dict.value">{{
              dict.label
            }}
            </el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="是否刷卡套餐" prop="isCard">
          <el-switch active-text="是" active-color="#085" :active-value="1" inactive-text="否" inactive-color="#f00"
            :inactive-value="0" v-model="form.isCard"></el-switch>
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { addCharge, delCharge, getCharge, listCharge, updateCharge, } from "@/api/equipment/charge";
import { listStation } from "@/api/equipment/station";
const { proxy } = getCurrentInstance();
const { charge_type, charge_mode } = proxy.useDict("charge_mode", "charge_type");

const loading = ref(true)
const ids = ref([])
const single = ref(true)
const multiple = ref(true)
const showSearch = ref(true)
const total = ref(0)
// 套餐表格数据
const infoList = ref([])
const title = ref('')
const open = ref(false)
const queryStat = ref({})
const station_list = ref({})
const queryParams = ref({
  pageNum: 1,
  pageSize: 10,
  stationId: null,
})
const form = ref({
  packageId: null,
  amount: 1,
  duration: 60,
  electricity: 1,
  chargeType: "ONCE",
  chargeMode: "TIME",
  // isCard: 0,
})

const stationId = ref(null)
const rules = ref({
  amount: [{ required: true, message: "预付金额不能为空", trigger: "blur" }],
  duration: [{ required: true, message: "预付时间不能为空", trigger: "blur" }],
  electricity: [
    { required: true, message: "预付电量不能为空", trigger: "blur" },
  ],
  chargeType: [
    { required: true, message: "套餐类型不能为空", trigger: "blur" },
  ],
  chargeMode: [
    { required: true, message: "计时模式不能为空", trigger: "blur" },
  ],
  isCard: [
    { required: true, message: "请选择是否为刷卡套餐", trigger: "blur" },
  ],
})


function getList() {
  loading.value = true;
  listCharge(queryParams.value).then((response) => {
    infoList.value = response.rows;
    total.value = response.total;
    loading.value = false;
  });
}

function getStation() {
  listStation(queryStat.value).then((response) => {
    station_list.value = response.rows;
    let find_data = station_list.value.find((item) => item.stationId == stationId.value)
    queryParams.value.stationId = find_data.stationId;
    getList();
  });
}

function cancel() {
  open.value = false;
  reset();
}

function reset() {
  form.value = {
    packageId: null,
    amount: 1,
    duration: 60,
    electricity: 1,
    chargeType: "ONCE",
    chargeMode: "TIME",
    isCard: 0,
  };
  proxy.resetForm("formRef");
}

function handleQuery() {
  queryParams.value.pageNum = 1;
  getList();
}

function resetQuery() {
  proxy.resetForm("queryForm");
  handleQuery();
}

function handleSelectionChange(selection) {
  ids.value = selection.map((item) => item.packageId);
  single.value = selection.length !== 1;
  multiple.value = !selection.length;
}
function handleAdd() {
  reset();
  open.value = true;
  title.value = "添加套餐";
}

function handleUpdate(row) {
  reset();
  open.value = true;
  title.value = "修改套餐";
  const packageId = row.packageId || ids.value;
  getCharge(packageId).then((response) => {
    form.value = response.data;
    form.amount.value = form.value.amount / 100;
    form.value.duration = form.value.duration / 60;
    form.value.electricity = parseFloat(
      form.value.electricity / 3600000
    ).toFixed(3);
  });
}


function submitForm() {
  proxy.$refs["formRef"].validate((valid) => {
    if (valid) {
      if (form.value.packageId != null) {
        updateCharge({
          packageId: form.value.packageId,
          amount: form.value.amount * 100,
          duration: form.value.duration * 60,
          electricity: form.value.electricity * 3600000,
          stationId: queryParams.value.stationId,
          isCard: form.value.isCard,
          chargeType: form.value.chargeType,
          chargeMode:
            form.value.chargeType == "WALLET"
              ? "TIME"
              : form.value.chargeMode,
        }).then((response) => {
          proxy.$modal.msgSuccess("修改成功");
          open.value = false;
          getList();
        });
      } else {
        addCharge({
          packageId: form.value.packageId,
          amount: form.value.amount * 100,
          duration: form.value.duration * 60,
          electricity: form.value.electricity * 3600000,
          stationId: queryParams.value.stationId,
          isCard: form.value.isCard,
          chargeType: form.value.chargeType,
          chargeMode:
            form.value.chargeType == "WALLET"
              ? "TIME"
              : form.value.chargeMode,
        }).then((response) => {
          proxy.$modal.msgSuccess("添加成功");
          open.value = false;
          getList();
        });
      }
    }
  });
}


function handleDelete(row) {
  const ids = [row.packageId] || ids.value;
  proxy.$modal
    .confirm('是否确认删除套餐编号为"' + ids + '"的数据项？')
    .then(function () {
      return delCharge(ids);
    })
    .then(() => {
      getList();
      proxy.$modal.msgSuccess("删除成功");
    })
    .catch(() => {
    });
}

stationId.value = proxy.$route.query.stationId;
getStation();
</script>

<style lang="scss" scoped>
#bmap {
  height: 300px;
}

.look {
  cursor: pointer;
}

.modify {
  display: block;
}
</style>
